package top.java.InetAddressTest;

import org.junit.Test;

import java.io.IOException;
import java.net.*;

/**
 *      UDP 协议的网络编程
 *
 *      系统不保证UDP数据报一定能够安全送到目的地，也不能确定什么时候可以抵达。
 */

public class UDPtest1 {

    //发送端
    @Test
    public void sender() throws IOException {

        //string.length() 和 string.getBytes().length
        //String. length () 是表示字符串所需的UTF-8代码单元的数量。  11
        //String. getBytes (). length 是在默认编码中表示字符串所需的字节数。   3+3*8=27

        String str = "UDP方式发送的字符串";
        byte[] bytes = str.getBytes();
        InetAddress inet = InetAddress.getByName("127.0.0.1");


        DatagramPacket packet =
                new DatagramPacket(bytes,0,bytes.length,inet,9090);

        DatagramSocket socket = new DatagramSocket();
        socket.send(packet);

        socket.close();
    }

    //接收端
    @Test
    public void raceiver() throws IOException {

        DatagramSocket socket = new DatagramSocket(9090);
        byte[] bytes = new byte[100];
        DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length);
        socket.receive(packet);
        System.out.println(new String(packet.getData(),0,packet.getLength()));
        socket.close();
    }
}
